﻿using System;

namespace PortableTPL
{
    public partial class Task<T> : Task
    {
        T result;

        public T Result
        {
            get
            {
                ThrowAggregateExceptionIfPresent(); 
                return result;
            }
        }

        public Task(Func<T> func)
        {
            ActionDelegate = (Delegate) func;
        }

        public Task(Func<object, T> func, object state)
        {
            ActionDelegate = (Delegate)func;
            AsyncState = state;
        }

        public Task(Func<T> func, CancellationToken token)
        {
            ActionDelegate = (Delegate)func;
            token.Register(OnCancellation);
        }

        public Task(Func<object, T> func, object state, CancellationToken token)
        {
            ActionDelegate = (Delegate)func;
            AsyncState = state;

            token.Register(OnCancellation);
        }

        protected override void ExecuteDelegate()
        {
            if (ActionDelegate.Method.GetParameters().Length > 0)
                result = (T)ActionDelegate.DynamicInvoke(AsyncState);
            else
                result = (T)ActionDelegate.DynamicInvoke();
        }
    }
}
